package re.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import re.entity.User;
import re.mapper.UserMapper;
import re.service.UserService;
import re.service.i.IUserService;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
public class HomeController {

    private static AtomicInteger id = new AtomicInteger(0);

    private static ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();

    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Qualifier("userService")
    private IUserService userService;

    @RequestMapping(value = "/home/{operate}", method = RequestMethod.GET, produces = { "application/json; charset=UTF-8" })
    public String home(@PathVariable String operate) {

        if(id.get() == 0) {
            int[] ids = userService.ids();
            id.set(ids[ids.length - 1]);
            for(int i : ids) deque.offer(i);
        }

        switch (operate) {
            case "i":
                User user = randomUser();
                userMapper.save(user);
                deque.add(id.incrementAndGet());
                return "insert => " + user.toString();
            case "u":
                if(deque.isEmpty()) {
                    return "update =>" + "there is no user for updateing";
                } else {
                    user = randomUser();
                    user.setId(deque.getFirst());
                    userMapper.update(user);
                    return "update =>" + user.toString();
                }
            case "d":
                if(deque.isEmpty()) {
                    return "delete => " + "there is no user fro deleteing";
                } else {
                    int id = deque.pop();
                    userService.delById(id);
                    return "delete => " + "userid " + id;
                }
            case "s":
                return userMapper.getAll().stream().map(User::toString).collect(Collectors.joining("\n"));
            default:
                return "ha?";
        }
    }

    private User randomUser() {

        User a = new User();

        a.setName(UUID.randomUUID().toString().substring(0, 6));

        a.setAddress(UUID.randomUUID().toString().substring(0, 6));

        return a;
    }
}
